package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl implements IApUnlikesBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveUnlikes(UnLikesBehaviorDto dto) {
        User user = AppThreadLocalUtil.get();
        ApUnlikesBehavior  behavior=new ApUnlikesBehavior();
        if(user!=null){
            behavior.setUserId(user.getUserId());
        }else{
            behavior.setEquipmentId(dto.getEquipmentId());
        }
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(dto.getType());
        behavior.setCreatedTime(new Date());
        //判断
        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if(user==null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else{
            query.equals(Criteria.where("userId").is(user.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if(one==null){
            mongoTemplate.save(behavior);
        }else{
            if(one.getType()!=dto.getType()){
                one.setType(dto.getType());
                mongoTemplate.save(one);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if(dto.getUserId()==null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else{
            query.equals(Criteria.where("userId").is(dto.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
